package org.cy.algorithm.chapter_02;

public class BinaryAdder {

    public static int addBianary(int a, int b) {
        int sum = 0;
        int carry = 0;
        for (int i = 0; i < 32; i++) {
            sum |= ((a & (1 << i)) ^ (b & (1 << i)) ^ (carry << 1));
            if (carry != 0) {
                carry = ((a & (1 << i)) | (b & (1 << i)) & (carry << 1));
            } else {
                carry = (a & (1 << i)) & (b & (1 << i));
            }
        }
//        System.out.printf("a = %s\n", Integer.toBinaryString(a));
//        System.out.printf("b = %s\n", Integer.toBinaryString(b));
//        System.out.printf("sum = %s\n", Integer.toBinaryString(sum));
//        System.out.printf("sum = %d, carry = %d\n", sum, carry);
        return sum;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j < 1000; j++) {
                int sum = addBianary(i, j);
                if (sum != (i + j)) {
                    System.out.printf("Oops");
                }
            }
        }
        System.out.println("OK");
    }
}
